package com.hss.questions.arr;

import java.util.ArrayList;

/**
 http://www.cyc2018.xyz/%E7%AE%97%E6%B3%95/%E5%89%91%E6%8C%87%20Offer%20%E9%A2%98%E8%A7%A3/29.%20%E9%A1%BA%E6%97%B6%E9%92%88%E6%89%93%E5%8D%B0%E7%9F%A9%E9%98%B5.html#%E8%A7%A3%E9%A2%98%E6%80%9D%E8%B7%AF

 按顺时针的方向，从外到里打印矩阵的值。下图的矩阵打印结果为：1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10
* */
public class ClockWisePrint2DArray {
    public static int[][] arr = {
            {1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10},
            {11, 12, 13, 14, 15},
            {16, 17, 18, 19, 20},
            {21, 22, 23, 24, 25}
    };

    public static void main(String[] args) {
        ArrayList<Integer>  arrayList = printMatrix(arr);
        for (Integer i : arrayList){
            System.out.println(String.valueOf(i));
        }
    }

    public  static  ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<>();

        int col = matrix[0].length;
        int row = matrix.length;

        int r1=0,r2= row-1;
        int c1=0,c2=col-1;
        while (r1<=r2&& c1<=c2){
            for (int i=c1;i<=c2;i++){
                result.add(arr[r1][i]);
            }
            for (int j=r1+1;j<=r2;j++){
                result.add(arr[j][c2]);
            }
            for (int k=c2-1;k>=c1;k--){
                result.add(arr[r2][k]);
            }
            for (int l=r2-1;l>r1;l--){
                result.add(arr[l][c1]);
            }
            r1++;
            c1++;
            r2--;
            c2--;

        }
        return result;
    }
}
